import classNames from "classnames";
import React, { createRef, useEffect, useState } from "react";
import defaultImg from "../../assets/default.png";
import "./index.scss";

interface Props extends React.ImgHTMLAttributes<HTMLImageElement> {
  className?: string;
  src?: string;
  text?: string;
  icon?: string;
}
export const Image = ({ src, ...rest }: Props) => {
  const [url, setImgUrl] = useState(src);
  const imgRef = createRef<HTMLImageElement>();
  useEffect(() => {
    if (!imgRef.current) return;
    imgRef.current.onerror = () => {
      setImgUrl(defaultImg);
    };
  }, []);
  useEffect(() => {
    setImgUrl(src);
  }, [src]);
  return <img {...rest} src={url} ref={imgRef}></img>;
};
/** 文件缩略图，图片错误展示文件类型图片 */
export const FileImage = ({ src, icon, ...rest }: Props) => {
  const [url, setImgUrl] = useState(src);
  const [error, setError] = useState(false);

  useEffect(() => {
    setImgUrl(src);
  }, [src]);

  if (error) {
    return <span className={`iconfont ${icon}`}></span>;
  }
  return <img {...rest} src={url} onError={() => setError(true)}></img>;
};

export const ImageWithText = ({ src, text, className, ...rest }: Props) => {
  const [imgError, setImgError] = useState(false);
  const imgRef = createRef<HTMLImageElement>();
  useEffect(() => {
    if (!imgRef.current) return;
    imgRef.current.onerror = () => {
      setImgError(true);
    };
    imgRef.current.onload = () => {
      setImgError(false);
    };
  }, [src]);
  return imgError || !src ? (
    <span className={classNames("text-img", className)} {...rest}>
      {text?.slice(0, 1)}
    </span>
  ) : (
    <img
      className={classNames(className)}
      {...rest}
      src={src}
      ref={imgRef}
    ></img>
  );
};
